package com.itheima.sms.sms.utils;


import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.util.*;
import java.util.Map.Entry;


/**
 * httpClient工具类
 *
 * @author llhuang10
 * @date 2021/7/21 17:48
 */
@Slf4j
public class HttpClientUtil {


    /**
     * 编码格式。发送编码格式统一用UTF-8
     */
    private static final String ENCODING = "UTF-8";

    /**
     * 设置连接超时时间，单位毫秒。
     */
    private static final int CONNECT_TIMEOUT = 600000;

    /**
     * 请求获取数据的超时时间(即响应时间)，单位毫秒。
     */
    private static final int SOCKET_TIMEOUT = 600000;


    /**
     * 设置从connect Manager(连接池)获取Connection超时时间，单位毫秒
     */
    private static final int CONNECTION_REQUEST_TIMEOUT = 10000;

    /**
     * 声明httpClient管理器对象(httpClient连接池)
     */
    private static PoolingHttpClientConnectionManager cm;

    /**
     * 设置请求参数配置
     */
    private static RequestConfig config;

    /**
     * 请求中头信息user-Agent数组
     */
    private static List<String> userAgentList;

    // 静态代码块会在被类加载的时候执行
    static {
        cm = new PoolingHttpClientConnectionManager();
        cm.setMaxTotal(200);
        cm.setDefaultMaxPerRoute(20);

        config = RequestConfig.custom()
                .setSocketTimeout(SOCKET_TIMEOUT)
                .setConnectTimeout(CONNECT_TIMEOUT)
                .setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT)
                .build();

        userAgentList = new ArrayList<>();
        userAgentList.add("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36");
        userAgentList.add("Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:73.0) Gecko/20100101 Firefox/73.0");
        userAgentList.add("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.5 Safari/605.1.15");
        userAgentList.add("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 Edge/16.16299");
        userAgentList.add("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36");
        userAgentList.add("Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:63.0) Gecko/20100101 Firefox/63.0");
    }

    /**
     * 发送get请求；不带请求头和请求参数
     *
     * @param url 请求地址
     * @return HttpClientResult
     */
    public static HttpClientResult doGet(String url) throws IOException, URISyntaxException {
        return doGet(url, null, null);
    }

    /**
     * 发送get请求；带请求参数
     *
     * @param url    请求地址
     * @param params 请求参数集合
     * @return HttpClientResult
     */
    public static HttpClientResult doGet(String url, Map<String, String> params) throws IOException, URISyntaxException {
        return doGet(url, null, params);
    }

    /**
     * 发送get请求；带请求头和请求参数
     *
     * @param url     请求地址
     * @param headers 请求头集合
     * @param params  请求参数集合
     * @return HttpClientResult
     */
    public static HttpClientResult doGet(String url, Map<String, String> headers, Map<String, String> params) throws URISyntaxException, IOException {
        // 从连接池中获取HttpClient对象
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).build();

        // 创建访问的地址
        URIBuilder uriBuilder = new URIBuilder(url);
        if (params != null) {
            Set<Entry<String, String>> entrySet = params.entrySet();
            for (Entry<String, String> entry : entrySet) {
                uriBuilder.setParameter(entry.getKey(), entry.getValue());
            }
        }

        // 创建http对象
        HttpGet httpGet = new HttpGet(uriBuilder.build());
        httpGet.setConfig(config);

        // 设置请求头
        packageHeader(headers, httpGet);
        // 创建httpResponse对象
        CloseableHttpResponse httpResponse = null;

        try {
            // 执行请求
            httpResponse = httpClient.execute(httpGet);
            // 获得响应结果
            return getHttpClientResult(httpResponse);
        } finally {
            // 释放资源
            release(httpResponse);
        }
    }

    /**
     * 发送post请求；不带请求头和请求参数
     *
     * @param url 请求地址
     * @return HttpClientResult
     */
    public static HttpClientResult doPost(String url) throws IOException {
        return doPost(url, null, new HashMap<>());
    }

    /**
     * 发送post请求；带请求参数
     *
     * @param url    请求地址
     * @param params 参数集合
     * @return HttpClientResult
     */
    public static HttpClientResult doPost(String url, Map<String, String> params) throws IOException {
        return doPost(url, null, params);
    }

    /**
     * 发送post请求；带Json请求参数
     *
     * @param url     请求地址
     * @param jsonStr json格式参数
     * @return HttpClientResult
     */
    public static HttpClientResult doPost(String url, String jsonStr) throws IOException {
        return doPost(url, null, jsonStr);
    }

    /**
     * 发送post请求；带请求头和请求参数
     *
     * @param url     请求地址
     * @param headers 请求头集合
     * @param params  请求参数集合
     * @return HttpClientResult
     */
    public static HttpClientResult doPost(String url, Map<String, String> headers, Map<String, String> params) throws IOException {
        // 创建httpClient对象
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).build();

        // 创建http对象
        HttpPost httpPost = new HttpPost(url);

        httpPost.setConfig(config);
        // 设置请求头
        httpPost.setHeader("User-Agent", userAgentList.get(new Random().nextInt(userAgentList.size())));
        httpPost.setHeader("Connection", "keep-alive");
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Accept-Language", "zh-CN,zh;q=0.9");
        httpPost.setHeader("Accept-Encoding", "gzip, deflate, br");
        packageHeader(headers, httpPost);
        // 封装请求参数
        packageParam(params, httpPost);
        // 创建httpResponse对象
        CloseableHttpResponse httpResponse = null;

        try {
            // 执行请求并获得响应结果
            httpResponse = httpClient.execute(httpPost);
            return getHttpClientResult(httpResponse);
        } finally {
            // 释放资源
            release(httpResponse);
        }
    }

    public static HttpClientResult doPost(String url, Map<String, String> headers, String jsonStr) throws IOException {
        // 创建httpClient对象
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).build();

        // 创建http对象
        HttpPost httpPost = new HttpPost(url);

        httpPost.setConfig(config);
        // 设置请求头
        httpPost.setHeader("User-Agent", userAgentList.get(new Random().nextInt(userAgentList.size())));
        httpPost.setHeader("Connection", "keep-alive");
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-Type", "application/json; charset=UTF-8");
        httpPost.setHeader("Accept-Language", "zh-CN,zh;q=0.9");
        httpPost.setHeader("Accept-Encoding", "gzip, deflate, br");
        packageHeader(headers, httpPost);

        httpPost.setEntity(new StringEntity(jsonStr, ENCODING));
        // 创建httpResponse对象
        CloseableHttpResponse httpResponse = null;

        try {
            // 执行请求并获得响应结果
            httpResponse = httpClient.execute(httpPost);
            return getHttpClientResult(httpResponse);
        } finally {
            // 释放资源
            release(httpResponse);
        }
    }

    /**
     * 发送put请求；不带请求参数
     *
     * @param url 请求地址
     * @return HttpClientResult
     */
    public static HttpClientResult doPut(String url) {
        return doPut(url);
    }

    /**
     * 发送put请求；带请求参数
     *
     * @param url    请求地址
     * @param params 参数集合
     * @return HttpClientResult
     */
    public static HttpClientResult doPut(String url, Map<String, String> params) throws IOException {
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).build();

        HttpPut httpPut = new HttpPut(url);
        httpPut.setConfig(config);
        packageParam(params, httpPut);
        CloseableHttpResponse httpResponse = null;

        try {
            httpResponse = httpClient.execute(httpPut);
            return getHttpClientResult(httpResponse);
        } finally {
            release(httpResponse);
        }
    }

    /**
     * 发送delete请求；不带请求参数
     *
     * @param url 请求地址
     * @return HttpClientResult
     */
    public static HttpClientResult doDelete(String url) throws IOException {
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).build();

        HttpDelete httpDelete = new HttpDelete(url);
        httpDelete.setConfig(config);
        CloseableHttpResponse httpResponse = null;

        try {
            // 执行请求
            httpResponse = httpClient.execute(httpDelete);
            return getHttpClientResult(httpResponse);
        } finally {
            release(httpResponse);
        }
    }

    /**
     * 发送delete请求；带请求参数
     *
     * @param url    请求地址
     * @param params 参数集合
     * @return HttpClientResult
     */
    public static HttpClientResult doDelete(String url, Map<String, String> params) throws IOException {
        if (params == null) {
            params = new HashMap<>(16);
        }

        params.put("_method", "delete");
        return doPost(url, params);
    }

    /**
     * Description: 封装请求头
     *
     * @param params     参数集合
     * @param httpMethod HttpRequestBase
     */
    public static void packageHeader(Map<String, String> params, HttpRequestBase httpMethod) {
        // 封装请求头
        if (params != null) {
            Set<Entry<String, String>> entrySet = params.entrySet();
            for (Entry<String, String> entry : entrySet) {
                // 设置到请求头到HttpRequestBase对象中
                httpMethod.setHeader(entry.getKey(), entry.getValue());
            }
        }
    }

    /**
     * Description: 封装请求参数
     *
     * @param params     请求参数
     * @param httpMethod HttpRequestBase
     */
    public static void packageParam(Map<String, String> params, HttpEntityEnclosingRequestBase httpMethod)
            throws UnsupportedEncodingException {
        // 封装请求参数
        if (params != null) {
            List<NameValuePair> nvps = new ArrayList<>();
            Set<Entry<String, String>> entrySet = params.entrySet();
            for (Entry<String, String> entry : entrySet) {
                nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }

            // 设置到请求的http对象中
            httpMethod.setEntity(new UrlEncodedFormEntity(nvps, ENCODING));
        }
    }

    /**
     * Description: 获得响应结果
     *
     * @param httpResponse 响应
     * @return HttpClientResult
     */
    public static HttpClientResult getHttpClientResult(CloseableHttpResponse httpResponse) throws IOException {

        // 获取返回结果
        if (httpResponse != null && httpResponse.getStatusLine() != null) {
            String content = "";
            if (httpResponse.getEntity() != null) {
                content = EntityUtils.toString(httpResponse.getEntity(), ENCODING);
            }
            return new HttpClientResult(httpResponse.getStatusLine().getStatusCode(), content);
        }
        return new HttpClientResult(HttpStatus.SC_INTERNAL_SERVER_ERROR);
    }

    /**
     * Description: 释放资源
     *
     * @param httpResponse httpResponse
     */
    public static void release(CloseableHttpResponse httpResponse) throws IOException {
        // 释放资源
        if (httpResponse != null) {
            log.info(" ========== 释放资源 success! ==========");
            httpResponse.close();
        } else {
            log.info(" ========== 释放资源 fail! ==========");
        }
    }


    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public static class HttpClientResult implements Serializable {

        private static final long serialVersionUID = 2168152194164783950L;

        /**
         * 响应状态码
         */
        private int code;

        /**
         * 响应数据
         */
        private String content;

        public HttpClientResult(int code) {
            this.code = code;
        }

        public HttpClientResult(String content) {
            this.content = content;
        }

    }

}

